package com.newworld.dmsapp2.activity;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.baoyz.swipemenulistview.SwipeMenu;
import com.baoyz.swipemenulistview.SwipeMenuCreator;
import com.baoyz.swipemenulistview.SwipeMenuItem;
import com.baoyz.swipemenulistview.SwipeMenuListView;
import com.baoyz.swipemenulistview.SwipeMenuListView.OnMenuItemClickListener;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.newworld.dmsapp2.BaseActivity;
import com.newworld.dmsapp2.LoginActivity;
import com.newworld.dmsapp2.R;
import com.newworld.dmsapp2.activity.serviceapply.WriteOutdoorPaperActivity;
import com.newworld.dmsapp2.bean.User;
import com.newworld.dmsapp2.fragment.adapter.HouseManageAdapter;
import com.newworld.dmsapp2.fragment.bean.HouseManage;
import com.newworld.dmsapp2.register.HouseProvingActivity;
import com.newworld.dmsapp2.register.UserMessageActivity;
import com.newworld.dmsapp2.ui.view.CustomDialog;
import com.newworld.dmsapp2.util.Config;
import com.newworld.dmsapp2.util.HttpUtil;
import com.newworld.dmsapp2.util.MyPreference;
import com.newworld.dmsapp2.util.SingleSample;
import com.newworld.dmsapp2.util.Tool;

public class HouseManageListActivity extends BaseActivity {

	private SwipeMenuListView swipelv;
	private ArrayList<HouseManage> housemanageList = new ArrayList<HouseManage>();
	private HouseManageAdapter houseManageAdapter;
	private User user;
	private ProgressBar progressBar;
	public static String HISTORY_STATUS;
	protected Context context;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_house_manage_list);
		initData();
		initViews();
		initEvents();
		init();
	}
	
	private void initData(){
		user = SingleSample.getInstance(this).getUser();
	}

	@Override
	protected void initViews() {
		// TODO Auto-generated method stub
		TextView titleView = (TextView) findViewById(R.id.titlebar_both_center_title);
		TextView righttx = (TextView) findViewById(R.id.titlebar_both_right_text);
		titleView.setText(Config.TITLE_HOUSE_MANAGEMENT);
		progressBar = (ProgressBar) findViewById(R.id.proBar_get_data);
		righttx.setText("+");
		righttx.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
		LinearLayout leftlayout = (LinearLayout) findViewById(R.id.titlebar_both_left_layout);
		leftlayout.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				onBackPressed();
			}
		});
		LinearLayout rightlayout = (LinearLayout) findViewById(R.id.titlebar_both_right_layout);
		rightlayout.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				UserMessageActivity.INTENT_FLAG = 1;
				WriteOutdoorPaperActivity.PUBLIC_FLAG = false;
				intentActivity(HouseManageListActivity.this,
						HouseProvingActivity.class);
			}
		});

		swipelv = (SwipeMenuListView) findViewById(R.id.housemanage_lv);
		SwipeMenuCreator creator = new SwipeMenuCreator() {

			@Override
			public void create(SwipeMenu menu) {
				// TODO Auto-generated method stub
				switch (menu.getViewType()) {
				case 0:
					createMenu1(menu);
					break;
				case 1:
					createMenu2(menu);
					break;
				case 2:
					break;
				default:
					break;
				}

			}

			private void createMenu1(SwipeMenu menu) {
				SwipeMenuItem item1 = new SwipeMenuItem(getApplicationContext());
				item1.setBackground(new ColorDrawable(Color.rgb(0xff, 0x00,
						0x00)));
				item1.setWidth(dp2px(90));
				item1.setIcon(getResources()
						.getDrawable(R.drawable.ic_noatatch));
				menu.addMenuItem(item1);
			}

			private void createMenu2(SwipeMenu menu) {
				SwipeMenuItem item1 = new SwipeMenuItem(getApplicationContext());
				item1.setBackground(new ColorDrawable(Color.rgb(0x30, 0xa4,
						0xee)));
				item1.setWidth(dp2px(90));
				item1.setIcon(getResources().getDrawable(R.drawable.ic_attach));
				menu.addMenuItem(item1);
			}

		};
		swipelv.setMenuCreator(creator);
		swipelv.setOnMenuItemClickListener(new OnMenuItemClickListener() {

			@Override
			public void onMenuItemClick(final int position, SwipeMenu menu,
					int index) {
				// TODO Auto-generated method stub
				if (housemanageList.get(position).getStatusType_typeCode()
						.equals(Config.HOUSE_MANAGEMENT_ATATCHED)) {
					switch (index) {
					case 0:
						// open

						final CustomDialog dialog = new CustomDialog(
								HouseManageListActivity.this);
						dialog.setTitle("房屋关联");
						dialog.setDetial("确定解除关联？");
						dialog.setLeftOnClick(new OnClickListener() {
							@Override
							public void onClick(View v) {
								dialog.dismiss();
							}
						});
						dialog.setRightOnClick(new OnClickListener() {
							@Override
							public void onClick(View v) {
								
								unRelateHouse(housemanageList.get(position)
										.getHouse_id());
								MyPreference.getInstance(context).setUserId(0);
								Intent intent = new Intent();
								intent.setClass(HouseManageListActivity.this,
										LoginActivity.class);
								intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
								startActivity(intent);
								dialog.dismiss(); 
							}

						});
						dialog.show();

						break;
					}
				} else {
					switch (index) {
					case 0:
						final CustomDialog dialog2 = new CustomDialog(
								HouseManageListActivity.this);
						dialog2.setTitle("房屋关联");
						dialog2.setDetial("是否关联房屋？");
						dialog2.show();
						dialog2.setLeftOnClick(new OnClickListener() {
							@Override
							public void onClick(View v) {
								dialog2.dismiss();
							}
						});

						dialog2.setRightOnClick(new OnClickListener() {
							@Override
							public void onClick(View v) {
								dialog2.dismiss();
								ownerRelateHouse(housemanageList.get(position)
										.getHouse_id());
							}

						});

						break;
					}

				}

			}
		});
		swipelv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					final int position, long arg3) {
				// TODO Auto-generated method stub

				// 如果用户身份是户主并且和管理的房屋是关联的状态，就可以进一步查询关联在此房屋的人员状态
				if (housemanageList.get(position).getStatusType_typeCode()
						.equals(Config.HOUSE_MANAGEMENT_ATATCHED)
						&& housemanageList.get(position)
								.getRelationType_typeCode()
								.equals(Config.HOUSE_RELATIONSHIP_HZ)) {
					Intent intent = new Intent(HouseManageListActivity.this,
							HouseManagePeopleListActivity.class);
					intent.putExtra("houseId", housemanageList.get(position)
							.getHouse_id());
					startActivity(intent);
					finish();
				}

			}

		});
	

	}

	private int dp2px(int dp) {
		return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
				getResources().getDisplayMetrics());
	}

	private void init() {
		// TODO Auto-generated method stub
		getHouseUserList();
	}

	// 获取关联列表信息
	private void getHouseUserList() {
		// TODO Auto-generated method stub
		// 请求列表信息
		new AsyncTask<Void, Void, Void>() {

			private String message;

			@Override
			protected void onPreExecute() {
				if (Tool.isNetworkAvailable(HouseManageListActivity.this)) {
					progressBar.setVisibility(View.VISIBLE);
				} else {
					Toast.makeText(HouseManageListActivity.this, "请检查网络连接！",
							Toast.LENGTH_SHORT).show();
				}
			}

			@Override
			protected Void doInBackground(Void... params) {
				if (Tool.isNetworkAvailable(HouseManageListActivity.this)) {
					try {
						String url = Config.SERVER_URL
								+ user.getFunctionlistFromUser(
										Config.FUNCTION_REAL_HOUSERELATELIST)
										.get(0).getFunctionUrl();
						// 注册请求
						Map<String, String> map = new HashMap<String, String>();
						map.put("functionCode",
								Config.FUNCTION_REAL_HOUSERELATELIST);
						String setsessionid = "";
						user = SingleSample.getInstance(
								HouseManageListActivity.this).getUser();
						if (null != user) {
							if (null != user.getSessionId()
									&& !user.getSessionId().equals("")) {
								setsessionid = user.getSessionId();
							}
						}
						String result = HttpUtil.postRequestSe(url, map,
								setsessionid);
						Log.e("获取关联的房屋列表result", result);
						if (new JSONObject(result).getString("flag").equals(
								"success")) {
							String rows = new JSONObject(result)
									.getString("rows");
							if (!rows.equals("")) {
								Type type = new TypeToken<List<HouseManage>>() {
								}.getType();
								Gson gson = new Gson();
								housemanageList = gson.fromJson(rows, type);
							} else {
								housemanageList = new ArrayList<HouseManage>();
							}
						}
						message = new JSONObject(result).getString("message");

					} catch (Exception e) {
						e.printStackTrace();
					}

				}

				return null;
			}

			@Override
			protected void onPostExecute(Void result) {
				Toast.makeText(HouseManageListActivity.this, message,
						Toast.LENGTH_SHORT).show();
				progressBar.setVisibility(View.INVISIBLE);
				if (housemanageList != null) {
					houseManageAdapter = new HouseManageAdapter(
							HouseManageListActivity.this, housemanageList);
					swipelv.setAdapter(houseManageAdapter);
				} else {
					housemanageList = new ArrayList<HouseManage>();
					houseManageAdapter = new HouseManageAdapter(
							HouseManageListActivity.this, housemanageList);
					swipelv.setAdapter(houseManageAdapter);
				}
			}
		}.execute(null, null, null);
	}

	public void setData(ArrayList<HouseManage> houselist) {
		housemanageList = houselist;

	}

	@Override
	protected void initEvents() {
		// TODO Auto-generated method stub

	}

	// 解关联
	private void unRelateHouse(final String houseId) {
		// TODO Auto-generated method stub
		new AsyncTask<Void, Void, Void>() {

			private String unRelateMessage;

			@Override
			protected void onPreExecute() {
				if (Tool.isNetworkAvailable(HouseManageListActivity.this)) {
					progressBar.setVisibility(View.VISIBLE);
				} else {
					Toast.makeText(HouseManageListActivity.this, "请检查网络连接！",
							Toast.LENGTH_SHORT).show();
				}
			}

			@Override
			protected Void doInBackground(Void... params) {
				if (Tool.isNetworkAvailable(HouseManageListActivity.this)) {
					try {
						// String url = Config.SERVER_URL
						// + user.getFunctionlistFromUser(
						// Config.FUNCTION_REAL_HOUSERELATELIST)
						// .get(0).getFunctionUrl();
						String url = Config.UNRELATE_HOUSE_URL;
						// 注册请求
						Map<String, String> map = new HashMap<String, String>();
						// map.put("functionCode",
						// Config.FUNCTION_REAL_HOUSERELATELIST);
						map.put("functionCode", "houseManage");
						map.put("houseId", houseId);
						String setsessionid = "";
						user = SingleSample.getInstance(
								HouseManageListActivity.this).getUser();
						if (null != user) {
							if (null != user.getSessionId()
									&& !user.getSessionId().equals("")) {
								setsessionid = user.getSessionId();
							}
						}
						String result = HttpUtil.postRequestSe(url, map,
								setsessionid);
						Log.e("解关联result", result);
						unRelateMessage = new JSONObject(result)
								.getString("message");

					} catch (Exception e) {
						e.printStackTrace();
					}

				}

				return null;
			}

			@Override
			protected void onPostExecute(Void result) {
				Toast.makeText(HouseManageListActivity.this, unRelateMessage,
						Toast.LENGTH_SHORT).show();
				// progressBar.setVisibility(View.INVISIBLE);
				// houseManageAdapter = new HouseManageAdapter(
				// HouseManageListActivity.this, housemanageList);
				// swipelv.setAdapter(houseManageAdapter);
				getHouseUserList();
			}
		}.execute(null, null, null);
	}

	private void ownerRelateHouse(final String houseId) {
		// TODO Auto-generated method stub
		new AsyncTask<Void, Void, Void>() {

			private String ownerRelateMessage;

			@Override
			protected void onPreExecute() {
				if (Tool.isNetworkAvailable(HouseManageListActivity.this)) {
					progressBar.setVisibility(View.VISIBLE);
				} else {
					Toast.makeText(HouseManageListActivity.this, "请检查网络连接！",
							Toast.LENGTH_SHORT).show();
				}
			}

			@Override
			protected Void doInBackground(Void... params) {
				if (Tool.isNetworkAvailable(HouseManageListActivity.this)) {
					try {
						// String url = Config.SERVER_URL
						// + user.getFunctionlistFromUser(
						// Config.FUNCTION_REAL_HOUSERELATELIST)
						// .get(0).getFunctionUrl();
						String url = Config.OWNER_RELATE_HOUSE_URL;
						// 注册请求
						Map<String, String> map = new HashMap<String, String>();
						// map.put("functionCode",
						// Config.FUNCTION_REAL_HOUSERELATELIST);
						map.put("functionCode", "houseManage");
						map.put("houseId", houseId);
						String setsessionid = "";
						user = SingleSample.getInstance(
								HouseManageListActivity.this).getUser();
						if (null != user) {
							if (null != user.getSessionId()
									&& !user.getSessionId().equals("")) {
								setsessionid = user.getSessionId();
							}
						}
						String result = HttpUtil.postRequestSe(url, map,
								setsessionid);
						Log.e("解关联result", result);
						ownerRelateMessage = new JSONObject(result)
								.getString("message");

					} catch (Exception e) {
						e.printStackTrace();
					}

				}

				return null;
			}

			@Override
			protected void onPostExecute(Void result) {
				Toast.makeText(HouseManageListActivity.this,
						ownerRelateMessage, Toast.LENGTH_SHORT).show();
				// progressBar.setVisibility(View.INVISIBLE);
				// houseManageAdapter = new HouseManageAdapter(
				// HouseManageListActivity.this, housemanageList);
				// swipelv.setAdapter(houseManageAdapter);
				// getHouseUserList();
//				if (housemanageList.size() > 1) {
					getHouseUserList();
//				} else {
//					Intent intent = new Intent(HouseManageListActivity.this,
//							LoginActivity.class);
//					startActivity(intent);
//					finish();
//				}

			}
		}.execute(null, null, null);
	}
	// @Override
	// public void onRefresh() {
	// TODO Auto-generated method stub

	// }

	// @Override
	// public void onLoadMore() {
	// TODO Auto-generated method stub

	// }
}